use eframe::egui;
use std::fs::File;
use std::io::Read;
use open::that;

struct PasswordApp {
    username: String,
    password: String,
    is_logged_in: bool,
    name: String,
    url: String,
    stored_username: String,
    stored_password: String,
    entries: Vec<(String, String, String, String)>,
    // 新增一个变量来跟踪哪个详情需要显示
    show_details_index: Option<usize>,
    // 新增一个变量来跟踪是否处于修改状态
    is_editing: bool,
    // 新增一个变量来存储要删除的索引
    index_to_remove: Option<usize>,
    // 新增一个变量来跟踪是否隐藏条目列表
    hide_entries_list: bool,
    // 新增变量用于存储原始数据，以便取消修改时恢复
    original_entry: Option<(String, String, String, String)>,
}

impl Default for PasswordApp {
    fn default() -> Self {
        PasswordApp {
            username: "zhanggang".to_string(),
            password: "zhanggang1997".to_string(),
            is_logged_in: false,
            name: String::new(),
            url: String::new(),
            stored_username: String::new(),
            stored_password: String::new(),
            entries: Vec::new(),
            show_details_index: None,
            is_editing: false,
            index_to_remove: Option::None,
            hide_entries_list: false,
            original_entry: None,
        }
    }
}

impl eframe::App for PasswordApp {
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        if!self.is_logged_in {
            egui::CentralPanel::default().show(ctx, |ui| {
                ui.heading("登录页面");
                let input_size = egui::vec2(400.0, 60.0); // 输入框大小放大一倍
                let button_size = egui::vec2(300.0, 80.0); // 按钮大小放大一倍
                ui.label("用户名:");
                ui.add(egui::TextEdit::singleline(&mut self.username).desired_width(input_size.x));
                ui.label("密码:");
                ui.add(egui::TextEdit::singleline(&mut self.password).desired_width(input_size.x));
                if ui.add(egui::Button::new("登录").min_size(button_size)).clicked() {
                    if self.username == "zhanggang" && self.password == "zhanggang1997" {
                        self.is_logged_in = true;
                        // 登录后调整窗口大小
                        _frame.set_window_size(egui::vec2(1200.0, 900.0));
                    }
                }
            });
        } else {
            egui::CentralPanel::default().show(ctx, |ui| {
                ui.heading("个人密码存储系统");

                // 左侧表单区域和右侧按钮区域
                ui.columns(2, |columns| {
                    // 左侧表单
                    let input_size = egui::vec2(200.0, 30.0); // 输入框大小
                    columns[0].label("名称:");
                    columns[0].add(egui::TextEdit::singleline(&mut self.name).desired_width(input_size.x));
                    columns[0].label("网址:");
                    columns[0].add(egui::TextEdit::singleline(&mut self.url).desired_width(input_size.x));
                    columns[0].label("用户名:");
                    columns[0].add(egui::TextEdit::singleline(&mut self.stored_username).desired_width(input_size.x));
                    columns[0].label("密码:");
                    columns[0].add(egui::TextEdit::singleline(&mut self.stored_password).desired_width(input_size.x));

                    // 右侧按钮区域
                    let button_size = egui::vec2(150.0, 40.0); // 放大按钮大小
                    if columns[1].add(egui::Button::new("增加").min_size(button_size)).clicked() {
                        if!self.name.is_empty() &&!self.url.is_empty() &&!self.stored_username.is_empty() &&!self.stored_password.is_empty() {
                            self.entries.push((self.name.clone(), self.url.clone(), self.stored_username.clone(), self.stored_password.clone()));
                            self.name.clear();
                            self.url.clear();
                            self.stored_username.clear();
                            self.stored_password.clear();
                        }
                    }
                    if columns[1].add(egui::Button::new("清空所有数据").min_size(button_size)).clicked() {
                        self.entries.clear();
                        self.show_details_index = None; // 清空数据时关闭详情
                        self.is_editing = false;
                        self.hide_entries_list = false;
                    }
                });

                ui.separator();

                ui.heading("已存储的条目");

                // 分为左侧条目列表和右侧详情区域
                ui.columns(2, |columns| {
                    // 左侧条目列表
                    if!self.hide_entries_list {
                        self.index_to_remove = None;
                        for (i, (name, url, _username, _password)) in self.entries.iter().enumerate() {
                            let button_size = egui::vec2(150.0, 40.0); // 按钮大小
                            columns[0].horizontal(|h| {
                                h.label(format!("{}: {}", i + 1, name));
                                if h.add(egui::Button::new("查看详情").min_size(button_size)).clicked() {
                                    if self.show_details_index == Some(i) {
                                        self.show_details_index = None; // 关闭详情
                                        self.is_editing = false;
                                        self.hide_entries_list = false;
                                    } else {
                                        self.show_details_index = Some(i); // 打开详情
                                        self.is_editing = false;
                                        self.hide_entries_list = true; // 隐藏条目列表
                                    }
                                }
                                if h.add(egui::Button::new("修改").min_size(button_size)).clicked() {
                                    if self.show_details_index == Some(i) {
                                        self.is_editing =!self.is_editing;
                                        self.hide_entries_list = self.is_editing;
                                        if self.is_editing {
                                            // 保存原始数据
                                            self.original_entry = self.entries.get(i).cloned();
                                        }
                                    } else {
                                        self.show_details_index = Some(i);
                                        self.is_editing = true;
                                        self.hide_entries_list = true;
                                        // 保存原始数据
                                        self.original_entry = self.entries.get(i).cloned();
                                    }
                                }
                                if h.add(egui::Button::new("删除").min_size(button_size)).clicked() {
                                    self.index_to_remove = Some(i);
                                }
                                // 新增打开网页按钮
                                if h.add(egui::Button::new("打开网页").min_size(button_size)).clicked() {
                                    if let Err(e) = that(url) {
                                        eprintln!("Failed to open URL: {}", e);
                                    }
                                }
                            });
                        }

                        // 在循环结束后进行删除操作
                        if let Some(index) = self.index_to_remove {
                            self.entries.remove(index);
                            if self.show_details_index == Some(index) {
                                self.show_details_index = None;
                                self.is_editing = false;
                                self.hide_entries_list = false;
                            }
                        }
                    }

                    // 右侧详情区域
                    if let Some(index) = self.show_details_index {
                        if let Some((name, url, username, password)) = self.entries.get_mut(index) {
                            columns[1].heading(format!("详情 - {}", name));
                            if self.is_editing {
                                let input_size = egui::vec2(200.0, 30.0);
                                columns[1].label("名称:");
                                columns[1].add(egui::TextEdit::singleline(name).desired_width(input_size.x));
                                columns[1].label("网址:");
                                columns[1].add(egui::TextEdit::singleline(url).desired_width(input_size.x));
                                columns[1].label("用户名:");
                                columns[1].add(egui::TextEdit::singleline(username).desired_width(input_size.x));
                                columns[1].label("密码:");
                                columns[1].add(egui::TextEdit::singleline(password).desired_width(input_size.x));

                                let button_size = egui::vec2(150.0, 40.0);
                                if columns[1].add(egui::Button::new("保存").min_size(button_size)).clicked() {
                                    // 保存修改后的数据
                                    self.is_editing = false;
                                    self.show_details_index = None;
                                    self.hide_entries_list = false;
                                    self.original_entry = None;
                                }
                                // 添加取消按钮
                                if columns[1].add(egui::Button::new("取消").min_size(button_size)).clicked() {
                                    if let Some(original) = self.original_entry.take() {
                                        *name = original.0;
                                        *url = original.1;
                                        *username = original.2;
                                        *password = original.3;
                                    }
                                    self.is_editing = false;
                                    self.show_details_index = None;
                                    self.hide_entries_list = false;
                                }
                            } else {
                                columns[1].label(format!("网址: {}", url));
                                columns[1].label(format!("用户名: {}", username));
                                columns[1].label(format!("密码: {}", password));

                                // 添加返回按钮
                                let button_size = egui::vec2(150.0, 40.0);
                                if columns[1].add(egui::Button::new("返回").min_size(button_size)).clicked() {
                                    self.show_details_index = None;
                                    self.is_editing = false;
                                    self.hide_entries_list = false;
                                }
                            }
                        }
                    }
                });
            });
        }
    }
}

fn main() {
    let options = eframe::NativeOptions {
        initial_window_size: Some(egui::vec2(800.0, 600.0)),
        ..Default::default()
    };

    let _ = eframe::run_native(
        "个人密码存储系统",
        options,
        Box::new(|cc| {
            if let Ok(mut file) = File::open("simsun.ttc") {
                let mut font_data = Vec::new();
                if file.read_to_end(&mut font_data).is_ok() {
                    let _font_id = egui::FontId::proportional(16.0);
                    let mut fonts = egui::FontDefinitions::default();
                    // 将 Vec<u8> 包装成 egui::FontData
                    let font_data_wrapper = egui::FontData::from_owned(font_data);
                    fonts.font_data.insert("simsun".to_string(), font_data_wrapper);
                    fonts.families.get_mut(&egui::FontFamily::Proportional).unwrap().insert(0, "simsun".to_string());
                    cc.egui_ctx.set_fonts(fonts);
                }
            }
            Box::new(PasswordApp::default())
        }),
    );
}